package com.yc.favorite.biz;

import com.yc.favorite.entity.Favorite;
import com.yc.favorite.entity.Tag;
import com.yc.favorite.entity.Tagfavorite;
import com.yc.favorite.mapper.FavoriteMapper;
import com.yc.favorite.mapper.TagMapper;
import com.yc.favorite.mapper.TagfavoriteMapper;
import com.yc.favorite.util.MyBatisHelper;
import com.yc.favorite.util.Utils;
import org.apache.ibatis.session.SqlSession;

// 业务类
public class FavoriteBiz {

    public void createFavorite(Favorite favorite)
            throws BizException {
        Utils.checkEmpty(favorite.getUid(), "请先登录系统!");
        if (favorite.getFlabel() == null
                || favorite.getFlabel().trim().isEmpty()) {
            throw new BizException("请输入链接名称");
        }
        Utils.checkEmpty(favorite.getFurl(), "请输入链接地址");
        Utils.checkEmpty(favorite.getFdesc(), "请输入链接描述");
        Utils.checkEmpty(favorite.getFtags(), "请输入链接分类");
        SqlSession sqlSession = MyBatisHelper.openSession();
        try {
            FavoriteMapper favoriteMapper = sqlSession.getMapper(FavoriteMapper.class);
            TagMapper tagMapper = sqlSession.getMapper(TagMapper.class);
            TagfavoriteMapper tagfavoriteMapper = sqlSession.getMapper(TagfavoriteMapper.class);
            favoriteMapper.insert(favorite);
            String[] tags = favorite.getFtags().split("[,;，；\\s]+");
            for (String tag : tags) {
                Tag t = tagMapper.selectByName(tag);
                if (t == null) {
                    // 数据库没有该分类, 创建新的分类
                    t = new Tag();
                    t.setTname(tag);
                    t.setTcount(1);
                    tagMapper.insert(t);
                } else {
                    // 数据库有该分类, 更新该分类的数量
                    t.setTcount(t.getTcount() + 1);
                    tagMapper.updateById(t);
                }
                // 新增中间表记录
                Tagfavorite tf = new Tagfavorite();
                tf.setTid(t.getTid());
                tf.setFid(favorite.getFid());
                tagfavoriteMapper.insert(tf);
            }
            sqlSession.commit();
        } catch (Exception e) {
            e.printStackTrace();
            sqlSession.rollback();
        } finally {
            sqlSession.close();
        }
    }

    public void deleteFavorite(int fid) {
        SqlSession sqlSession = MyBatisHelper.openSession();
        try {
            FavoriteMapper favoriteMapper = sqlSession.getMapper(FavoriteMapper.class);
            TagMapper tagMapper = sqlSession.getMapper(TagMapper.class);
            TagfavoriteMapper tagfavoriteMapper = sqlSession.getMapper(TagfavoriteMapper.class);
            favoriteMapper.deleteById(fid);
            tagfavoriteMapper.deleteByFid(fid);
            tagMapper.updateTcountByFid(fid);
            sqlSession.commit();
        } catch (Exception e) {
            sqlSession.rollback();
        } finally {
            sqlSession.close();
        }
    }
}